<template>
  <div id="imageDetailPage">
    <a-row :gutter="[16, 16]" style="justify-content: center">
      <!-- 图片展示区 -->
      <a-col :sm="24" :md="10" :xl="10">
        <a-card title="图片详情">
          <a-image
            style="max-width: 500px; object-fit: contain"
            :src="image.url + '?x-oss-process=image/format,webp'"
          />
        </a-card>
      </a-col>
      <!-- 图片信息区 -->
      <a-col :sm="24" :md="6" :xl="5">
        <a-card title="图片信息">
          <a-descriptions :column="1">
            <a-descriptions-item label="作者">
              <a-space>
                <a-avatar :size="24" :src="image.user?.userAvatar" />
                <div>{{ image.user?.userName }}</div>
              </a-space>
            </a-descriptions-item>
            <a-descriptions-item label="名称">
              {{ image.name ?? '未命名' }}
            </a-descriptions-item>
            <a-descriptions-item label="简介">
              {{ image.introduction ?? '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="分类">
              {{ image.category ?? '默认' }}
            </a-descriptions-item>
            <a-descriptions-item label="标签">
              <a-tag v-for="tag in image.tags" :key="tag">
                {{ tag }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="格式">
              {{ image.imgFormat ?? '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="宽度">
              {{ image.imgWidth ?? '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="高度">
              {{ image.imgHeight ?? '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="宽高比">
              {{ image.imgScale ?? '-' }}
            </a-descriptions-item>
            <a-descriptions-item label="大小">
              {{ formatSize(image.imgSize) }}
            </a-descriptions-item>
            <a-descriptions-item label="主色调">
              <a-space>
                <div
                  v-if="image.imgColor"
                  :style="{
                    backgroundColor: toHexColor(image.imgColor),
                    width: '16px',
                    height: '16px',
                  }"
                />
                {{ image.imgColor ?? '-' }}
              </a-space>
            </a-descriptions-item>
          </a-descriptions>
          <a-space wrap>
            <a-button :icon="h(EditOutlined)" v-if="canEdit" type="default" @click="doEdit">
              编辑
            </a-button>
            <a-button :icon="h(DeleteOutlined)" v-if="canDelete" danger @click="doDelete">
              删除
            </a-button>
            <a-button :icon="h(DownloadOutlined)" type="primary" shape="round" @click="doDownload">
              下载
            </a-button>
            <a-button :icon='h(ShareAltOutlined)' type="primary" ghost @click="doShare">
              分享
            </a-button>
          </a-space>
        </a-card>
      </a-col>
    </a-row>
    <ShareModal ref="shareModalRef" :link="shareLink" />
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, h, ref } from 'vue'
import { EditOutlined, DeleteOutlined, DownloadOutlined, ShareAltOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { deleteImageUsingPost, getImageVoByIdUsingPost } from '@/api/imageController.ts'
import { downloadImage, formatSize, toHexColor } from '../../utils'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import router from '@/router'
import ShareModal from '@/components/ShareModal.vue'
import { SPACE_PERMISSION_ENUM } from '@/constants/spaceUser.ts'

// 路由参数
const props = defineProps<{
  id: string | number
}>()
// 图片详情信息
const image = ref<API.ImageVO>({})

// 获取图片详情
const fetchPictureDetail = async () => {
  try {
    const res = await getImageVoByIdUsingPost({
      id: props.id as number,
    })
    if (res.data.code === 0 && res.data.data) {
      image.value = res.data.data
    } else {
      message.error('获取图片详情失败，' + res.data.message)
    }
  } catch (e: any) {
    message.error('获取图片详情失败：' + e.message)
  }
}

// 通用权限检查函数
function createPermissionChecker(permission: string) {
  return computed(() => {
    return (image.value.permissionList ?? []).includes(permission)
  })
}

// 定义权限检查
const canEdit = createPermissionChecker(SPACE_PERMISSION_ENUM.IMAGE_EDIT)
const canDelete = createPermissionChecker(SPACE_PERMISSION_ENUM.IMAGE_DELETE)

// 编辑
const doEdit = () => {
  router.push({
    path: '/image/add',
    query: {
      id: image.value.id,
      spaceId: image.value.spaceId,
    },
  })
}

// 删除
const doDelete = async () => {
  const id = image.value.id
  if (!id) {
    return
  }
  const res = await deleteImageUsingPost({ id })
  if (res.data.code === 0) {
    message.success('删除图片成功')
    // 跳转回主页
    router.push({
      path: '/',
      replace: true,
    })
  } else {
    message.error('删除图片失败')
  }
}

// 处理下载
const doDownload = () => {
  let url = image.value.url
  // 处理下载的图片没有后缀名
  if (url && url.charAt(url.length - 1) === '.') {
    url = url + '?x-oss-process=image/format,' + image.value.imgFormat
  }
  downloadImage(url)
}

onMounted(() => {
  fetchPictureDetail()
})

// 分享弹窗引用
const shareModalRef = ref()
// 分享链接
const shareLink = ref<string>()

// 分享
const doShare = () => {
  shareLink.value = `${window.location.protocol}//${window.location.host}/image/detail/${image.value.id}`
  if (shareModalRef.value) {
    shareModalRef.value.openModal()
  }
}
</script>
